/*=============================================================================

  Library: HMPBundleFrame

  Copyright (c) German Cancer Research Center,
    Division of Medical and Biological Informatics

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=============================================================================*/

#include <QStringList>
#include <QHash>

#include "IBundle.h"
#include "Bundle_p.h"
#include "IBundleContext.h"
#include "BundleContext_p.h"
#include "BundleFrameworkUtil_p.h"
#include "BundleArchive_p.h"
#include "BundleFrameworkContext_p.h"
#include "Services_p.h"
#include "Utils.h"

//----------------------------------------------------------------------------
IBundle::IBundle()
: d_ptr(0)
{

}

//----------------------------------------------------------------------------
void IBundle::init(BundlePrivate* dd)
{
  if (d_ptr) throw IllegalStateException("Bundle already initialized");
  d_ptr = dd;
}

//----------------------------------------------------------------------------
void IBundle::init(const QWeakPointer<IBundle>& self,
                     BundleFrameworkContext* fw,
                     QSharedPointer<BundleArchive> pa)
{
  if (d_ptr) throw IllegalStateException("Bundle already initialized");
  d_ptr = new BundlePrivate(self, fw, pa);
}

//----------------------------------------------------------------------------
IBundle::~IBundle()
{
  delete d_ptr;
}

//----------------------------------------------------------------------------
IBundle::State IBundle::getState() const
{
  Q_D(const Bundle);
    return d->state;
}

bool IBundle::getIsResolved() const
{
    Q_D(const Bundle);
    return (RESOLVED & d->state) ? true : false;
}

bool IBundle::getIsActive() const
{
    Q_D(const Bundle);
    return (ACTIVE & d->state) ? true : false;
}

bool IBundle::getIsStarted() const
{
    Q_D(const Bundle);
    return (STARTING & d->state) ? true : false;
}

const char *IBundle::getPath() const
{
    return getLocation().toStdString().c_str();
}

const char *IBundle::getName() const
{
    // add by txy on 20190116
    IBundle *pBundle = (IBundle*)this;
    QHash<QString, QString> headerHash = pBundle->getHeaders();
    QString str = headerHash.value("Plugin-Name");

    return str.toStdString().c_str();
}

const char *IBundle::getSymbolicName() const
{
//  Q_D(const Bundle);
  //返回引用，不能返回局部变量，增加一个全局变量
//  d->symbolicName_std = d->symbolicName.toStdString();

    return qt_getSymbolicName().toStdString().c_str();
}

const char *IBundle::getVendor() const
{
    // add by txy on 20190116
    IBundle *pBundle = (IBundle*)this;
    QHash<QString, QString> headerHash = pBundle->getHeaders();
    QString str = headerHash.value("Plugin-Vendor");

    return str.toStdString().c_str();
}

const char *IBundle::getCopyright() const
{
    // add by txy on 20190116
    IBundle *pBundle = (IBundle*)this;
    QHash<QString, QString> headerHash = pBundle->getHeaders();
    QString str = headerHash.value("Plugin-Copyright");

    return str.toStdString().c_str();
}

const char *IBundle::getActivatorClass() const
{
    IBundle *pBundle = (IBundle*)this;
    QHash<QString, QString> headerHash = pBundle->getHeaders();
    QString str = headerHash.value("Plugin-Activator");

    return str.toStdString().c_str();
}

const char *IBundle::getActivatorLibrary() const
{
    IBundle *pBundle = (IBundle*)this;
    QHash<QString, QString> headerHash = pBundle->getHeaders();
    QString str = headerHash.value("Plugin-Library");

    return str.toStdString().c_str();
}

IBundleActivator *IBundle::getActivator() const
{
    Q_D(const Bundle);

    return d->pluginActivator;
}

IBundleContext *IBundle::getBundleContext() const
{
    return getPluginContext();
}

bool IBundle::getLazyStart() const
{
    // add by txy on 20190116
    IBundle *pBundle = (IBundle*)this;
    QHash<QString, QString> headerHash = pBundle->getHeaders();
    QString str = headerHash.value("Plugin-ActivationPolicy");
    if(str == "lazy")
        return true;
    else
        return false;
}








//----------------------------------------------------------------------------
void IBundle::start(const StartOptions& options)
{
  Q_D(Bundle);

  if (d->state == UNINSTALLED)
  {
    throw IllegalStateException("Bundle is uninstalled");
  }

  // Initialize the activation; checks initialization of lazy
  // activation.

  //TODO 1: If activating or deactivating, wait a litle
  // we don't use mutliple threads to start plugins for now
  //waitOnActivation(lock, "Plugin::start", false);

  //2: start() is idempotent, i.e., nothing to do when already started
  if (d->state == ACTIVE)
  {
    return;
  }

  //3: Record non-transient start requests.
  if ((options & START_TRANSIENT) == 0)
  {
    d->setAutostartSetting(options);
  }

  //4: Resolve plugin (if needed)
  d->getUpdatedState();

  //5: Eager?
  if ((options & START_ACTIVATION_POLICY) && !d->eagerActivation )
  {
    if (STARTING == d->state) return;
    d->state = STARTING;
    d->pluginContext.reset(new IBundleContext(this->d_func()));
    BundleEvent pluginEvent(BundleEvent::LAZY_ACTIVATION, d->q_ptr);
    d->fwCtx->listeners.emitPluginChanged(pluginEvent);
  }
  else
  {
#if 0
      try
      {
        d->finalizeActivation();
      }
      catch(const BundleException &e)
      {
          qDebug() << e.what();
      }
      catch(const Exception &e)
      {
          qDebug() << e.what();
      }
#else
      d->finalizeActivation();
#endif


  }
}

//----------------------------------------------------------------------------
void IBundle::stop(const StopOptions& options)
{
  Q_D(Bundle);

  const RuntimeException* savedException = 0;

  //1:
  if (d->state == UNINSTALLED)
  {
    throw IllegalStateException("Bundle is uninstalled");
  }

  // 2: If an operation is in progress, wait a little
  d->waitOnOperation(&d->operationLock, "Plugin::stop", false);

  //3:
  if ((options & STOP_TRANSIENT) == 0)
  {
    d->ignoreAutostartSetting();
  }

  switch (d->state)
  {
  case INSTALLED:
  case RESOLVED:
  case STOPPING:
  case UNINSTALLED:
    //4:
    return;

  case ACTIVE:
  case STARTING: // Lazy start...
    savedException = d->stop0();
    break;
  };

  if (savedException != 0)
  {
    if (const BundleException* pluginExc = dynamic_cast<const BundleException*>(savedException))
    {
      BundleException pe(*pluginExc);
      delete savedException;
      throw pe;
    }
    else
    {
      RuntimeException re(*savedException);
      delete savedException;
      throw re;
    }
  }
}

//----------------------------------------------------------------------------
void IBundle::update(const QUrl& updateLocation)
{
  Q_D(Bundle);
  BundlePrivate::Locker sync(&d->operationLock);
  const bool wasActive = d->state == ACTIVE;

  switch (d->getUpdatedState_unlocked())
  {
  case ACTIVE:
    stop(STOP_TRANSIENT);
    // Fall through
  case RESOLVED:
  case INSTALLED:
    // Load new plugin
    //secure.callUpdate0(this, in, wasActive);
    d->update0(updateLocation, wasActive);
    break;
  case STARTING:
    // Wait for RUNNING state, this doesn't happen now
    // since we are synchronized.
    throw IllegalStateException("Bundle is in STARTING state");
  case STOPPING:
    // Wait for RESOLVED state, this doesn't happen now
    // since we are synchronized.
    throw IllegalStateException("Bundle is in STOPPING state");
  case UNINSTALLED:
    throw IllegalStateException("Bundle is in UNINSTALLED state");
  }
}
//----------------------------------------------------------------------------
void IBundle::uninstall()
{
  Q_D(Bundle);
  {
    BundlePrivate::Locker sync(&d->operationLock);

    if (d->archive)
    {
      try
      {
        d->archive->setStartLevel(-2); // Mark as uninstalled
      }
      catch (...)
      { }
    }

    switch (d->state)
    {
    case UNINSTALLED:
      throw IllegalStateException("Bundle is in UNINSTALLED state");

    case STARTING: // Lazy start
    case ACTIVE:
    case STOPPING:
    {
      const RuntimeException* exception = 0;
      try
      {
        d->waitOnOperation(&d->operationLock, "Plugin::uninstall", true);
        if (d->state & (ACTIVE | STARTING))
        {
          exception = d->stop0();
        }
      }
      catch (const Exception& e)
      {
        // Force to install
        d->setStateInstalled(false);
        d->operationLock.wakeAll();
        exception = new RuntimeException("Stopping plug-in failed", e);
      }
      d->operation.fetchAndStoreOrdered(BundlePrivate::UNINSTALLING);
      if (exception != 0)
      {
        d->fwCtx->listeners.frameworkError(this->d_func()->q_func(), *exception);
        delete exception;
      }
    }
      // Fall through
    case RESOLVED:
    case INSTALLED:
      d->fwCtx->plugins->remove(d->location);
      if (d->operation.fetchAndAddOrdered(0) != BundlePrivate::UNINSTALLING)
      {
        try
        {
          d->waitOnOperation(&d->operationLock, "Plugin::uninstall", true);
          d->operation.fetchAndStoreOrdered(BundlePrivate::UNINSTALLING);
        }
        catch (const BundleException& pe)
        {
          // Make sure that the context is invalid
          if (d->pluginContext != 0)
          {
            d->pluginContext->d_func()->invalidate();
            d->pluginContext.reset();
          }
          d->operation.fetchAndStoreOrdered(BundlePrivate::UNINSTALLING);
          d->fwCtx->listeners.frameworkError(this->d_func()->q_func(), pe);
        }
      }

      d->state = INSTALLED;
      // TODO: use thread
      // bundleThread().bundleChanged(new BundleEvent(BundleEvent.UNRESOLVED, this));
      d->fwCtx->listeners.emitPluginChanged(BundleEvent(BundleEvent::UNRESOLVED, d->q_func()));
      d->cachedHeaders = getHeaders();
      d->pluginActivator = 0;
      d->state = UNINSTALLED;

      // Purge old archive
      if (d->archive)
      {
        //d->archive->purge();
      }
      d->operation.fetchAndStoreOrdered(BundlePrivate::IDLE);

      if (d->pluginDir.exists())
      {
        if (!HMP::removeDirRecursively(d->pluginDir.absolutePath()))
        {
          d->fwCtx->listeners.frameworkError(this->d_func()->q_func(), RuntimeException("Failed to delete plugin data"));
        }
        d->pluginDir.setFile("");
      }

      // id, location and headers survive after uninstall.

      // There might be plug-in threads that are running start or stop
      // operations. This will wake them and give them a chance to terminate.
      d->operationLock.wakeAll();
      break;
    }
	d->pluginLoader.unload();
  }
  d->fwCtx->listeners.emitPluginChanged(BundleEvent(BundleEvent::UNINSTALLED, d->q_ptr));
}

//----------------------------------------------------------------------------
IBundleContext* IBundle::getPluginContext() const
{
  //TODO security checks
  Q_D(const Bundle);
    return d->pluginContext.data();
}

void IBundle::getRegisteredServices(std::vector<IServiceReference> &services)
{
    Q_D( Bundle);

    return d->getRegisteredServices(services);
}

//----------------------------------------------------------------------------
long IBundle::getBundleId() const
{
  Q_D(const Bundle);
  return d->id;
}

//----------------------------------------------------------------------------
QString IBundle::getLocation() const
{
  //TODO security
  Q_D(const Bundle);
  return d->location;
}

//----------------------------------------------------------------------------
QHash<QString, QString> IBundle::getHeaders()
{
  //TODO security
  Q_D(Bundle);
  if (d->cachedRawHeaders.empty())
  {
    d->cachedRawHeaders = d->archive->getUnlocalizedAttributes();
  }

  if (d->state == UNINSTALLED)
  {
    return d->cachedHeaders;
  }

  //TODO use the embedded .qm files to localize header values
  return d->cachedRawHeaders;
}

//----------------------------------------------------------------------------
QString IBundle::qt_getSymbolicName() const
{
  Q_D(const Bundle);
  return d->symbolicName;
}

//----------------------------------------------------------------------------
QStringList IBundle::getResourceList(const QString& path) const
{
  Q_D(const Bundle);
  return d->archive->findResourcesPath(path);
}

//----------------------------------------------------------------------------
QStringList IBundle::findResources(const QString& path,
                                     const QString& pattern, bool recurse) const
{
  Q_D(const Bundle);
  return d->findResourceEntries(path, pattern, recurse);
}

//----------------------------------------------------------------------------
QByteArray IBundle::getResource(const QString& path) const
{
  Q_D(const Bundle);
  return d->archive->getPluginResource(path);
}

//----------------------------------------------------------------------------
BundleLocalization IBundle::getPluginLocalization(
  const QLocale& locale, const QString& base) const
{
  Q_D(const Bundle);

  // There are five searching candidates possible:
  // base +
  //    "_" + language1 + "_" + country1 + ".qm"
  // or "_" + language1 + ".qm"
  // or "_" + language2 + "_" + country2 + ".qm"
  // or "_" + language2 + ".qm"
  // or ""  + ".qm"
  //
  // Where language1[_country1[_variation1]] is the requested locale,
  // and language2[_country2[_variation2]] is the default locale.

  QChar localeSep('_');
  QChar baseSep('_');

  QStringList searchCandidates;

  QStringList localeParts = locale.name().split(localeSep);
  QStringList defaultParts = QLocale().name().split(localeSep);

  searchCandidates << baseSep + localeParts[0] + localeSep + localeParts[1];
  searchCandidates << baseSep + localeParts[0];
  searchCandidates << baseSep + defaultParts[0] + localeSep + defaultParts[1];
  searchCandidates << baseSep + defaultParts[0];
  searchCandidates << "";

  QString localizationPath = base.left(base.lastIndexOf('/'));
  QStringList resourceList = this->getResourceList(localizationPath);

  foreach(QString resource, resourceList)
  {
    foreach(QString candidate, searchCandidates)
    {
      if (resource.endsWith(candidate + ".qm"))
      {
        return BundleLocalization(localizationPath + '/' + resource, locale, d->q_ptr);
      }
    }
  }

  return BundleLocalization();
}

//----------------------------------------------------------------------------
Version IBundle::getVersion() const
{
  Q_D(const Bundle);
  return d->version;
}

//----------------------------------------------------------------------------
QDebug operator<<(QDebug debug, IBundle::State state)
{
  switch (state)
  {
  case IBundle::UNINSTALLED:
    return debug << "UNINSTALLED";
  case IBundle::INSTALLED:
    return debug << "INSTALLED";
  case IBundle::RESOLVED:
    return debug << "RESOLVED";
  case IBundle::STARTING:
    return debug << "STARTING";
  case IBundle::STOPPING:
    return debug << "STOPPING";
  case IBundle::ACTIVE:
    return debug << "ACTIVE";
  default:
    return debug << "unknown";
  }
}

//----------------------------------------------------------------------------
QDebug operator<<(QDebug debug, const IBundle& plugin)
{
  debug.nospace() << "Plugin[" << "id=" << plugin.getBundleId() <<
      ", state=" << plugin.getState() << ", loc=" << plugin.getLocation() <<
      ", symName=" << plugin.qt_getSymbolicName() << "]";
  return debug.maybeSpace();
}

//----------------------------------------------------------------------------
QDebug operator<<(QDebug debug, IBundle const * plugin)
{
  return operator<<(debug, *plugin);
}

//----------------------------------------------------------------------------
LogStream& operator<<(LogStream& stream, IBundle const * plugin)
{
  stream << plugin->qt_getSymbolicName();
  return stream;
}

//----------------------------------------------------------------------------
LogStream& operator<<(LogStream& stream, const QSharedPointer<IBundle>& plugin)
{
  return operator<<(stream, plugin.data());
}
